package c.x.jy.admin.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import c.x.jy.common.annotation.SysLog;
import c.x.jy.common.utils.Constant;
import c.x.jy.common.utils.GetClassinfo;
import c.x.jy.dao.entity.BusinessEntity;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.service.BusinessService;
import c.x.jy.service.service.SysUserRoleService;
import c.x.jy.service.utils.SpringContextUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import c.x.jy.dao.entity.SysUserEntity;
import c.x.jy.service.service.SysUserService;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.R;



/**
 * 系统用户
 *
 * @author amwhyh
 * @email xxx@xx.com
 * @date 2021-05-20 20:20:23
 */
@RestController
@RequestMapping("sys/sysuser")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private Cache redisUtils;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BusinessService businessService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:sysuser:list")
    public R list(@RequestParam Map<String, Object> params){
     	if(getUser().getBusinessId()>0) {
    		params.put("businessId", getUser().getBusinessId());
    	}
        PageUtils page = sysUserService.queryPage(params);

        return R.put(page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:sysuser:info")
    public R info(@PathVariable("userId") Long userId,Long businessId){
        if(!getUser().getBusinessId().equals(0l))businessId=getUser().getBusinessId();

        SysUserEntity sysUser = sysUserService.getById(userId);
        if(!sysUser.getBusinessId().equals(businessId))return R.ok();
        return R .put(sysUser);
    }

    /**
     * 保存
     */

    @SysLog("添加系统用户")
    @Transactional
    @RequestMapping(value="/save" ,method= RequestMethod.POST)
    @RequiresPermissions("sys:sysuser:save")
    public R save(@RequestBody SysUserEntity sysUser){

        //非商家管理员不充许添加用户
        if(getUser().getBusinessId().equals(0l)&&sysUser.getBusinessId()==null) {
            return R.error("非商家管理员不充许添加用户");
        }
        if(sysUser.getBusinessId()==null)   sysUser.setBusinessId(getUser().getBusinessId());
        BusinessEntity b=  businessService.getById(sysUser.getBusinessId());
        if(b==null||b.getStatus().equals(0))	return R.error("商家已注销！");
        if(sysUser.getStatus()==null)sysUser.setStatus(0);
        sysUser.setCreateTime(new Date());
        sysUser.setCreateUserId(getUserId());
        sysUser.setBusinessId(sysUser.getBusinessId());
        sysUserService.save(sysUser);
        if(!StringUtils.isEmpty(sysUser.getRoleIds())) {
            sysUserRoleService.setRoleUser(sysUser.getUserId(),Arrays.asList(sysUser.getRoleIds().split(",")));
        }
        sysUserService.restPassword(sysUser.getUserId());
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改用户信息")
    @Transactional
    @PostMapping("/update")
    @RequiresPermissions("sys:sysuser:update")
    public R update(@RequestBody SysUserEntity sysUser){

        SysUserEntity user=	sysUserService.getById(sysUser.getUserId());
        if(user.getBusinessId().equals(Constant.SUPER_ADMIN)) {
            return	R.error("超级管理员不充许更改信息");

        }
        sysUser.setBusinessId(null);
        sysUser.setUsername(null);
        sysUser.setPassword(null);
        sysUser.setSalt(null);

        if(sysUser.getStatus()!=null&&sysUser.getStatus().equals(0)&&sysUser.getUserId().equals(getUserId())) {
            return	R.error("不自己踢自己下线！");
        }
        sysUserService.updateById(sysUser);
        if(sysUser.getStatus()!=null&&sysUser.getStatus().equals(0)) {

            Set<String> keys=	redisUtils.keys(Constant.USERKEY+sysUser.getUserId()+":*");
            if(keys!=null) keys.forEach(k->{ if(k!=null)redisUtils.remove( redisUtils.get(k));  }  );
        }

        if(!StringUtils.isEmpty(sysUser.getRoleIds())) {
            sysUserRoleService.setRoleUser(sysUser.getUserId(),Arrays.asList(sysUser.getRoleIds().split(",")));
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("本人修改用户信息")

    @PostMapping("/myupdate")

    public R myupdate(@RequestBody SysUserEntity user){

        //	SysUserEntity user=	sysUserService.getById(getUser().getUserId());

        user.setBusinessId(null);
        user.setUsername(null);
        user.setPassword(null);
        user.setSalt(null);

        user.setUserId(getUserId());

        sysUserService.updateById(user);
        user=	sysUserService.getById(getUser().getUserId());
        logger.info(JSON.toJSONString(user));
        user.setPassword(null);
        user.setSalt(null);

        GetClassinfo.ObjectChangeToObject(user,getUser());

        return R.put(getUser());
    }


    /**
     * 删除
     */
    @SysLog("删除用户")
    @RequestMapping(value="/user/{userId}",method = RequestMethod.DELETE)
    @RequiresPermissions("sys:sysuser:delete")
    public R delete(@PathVariable("userId") Long userId){
        SysUserEntity user = sysUserService.getById(userId);
        if(user.getBusinessId().equals(Constant.SUPER_ADMIN)) {
            return	R.error("超级管理员不充许删除");

        }
        if(userId.equals(getUserId())) {
            return	R.error("不能删除自己！");
        }
        sysUserService.removeByIds(Arrays.asList(userId));

        return R.ok();
    }

    /**
     *当前用户
     */
    @RequestMapping("/current")
    public R current(){
        return R .put(  SecurityUtils.getSubject().getPrincipal() ) ;
    }

    @RequestMapping("/checkUsername")
    @RequiresPermissions("sys:sysuser:info")
    public R checkUsername( String username){
        if(StringUtils.isEmpty(username))R.error("用户名不能为空");
        QueryWrapper<SysUserEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username", username);
        int i =sysUserService.count(queryWrapper);
        return i>0?R.error("该用户名已经存在！"):R.ok();

    }


}

